<template>
    <div class="cart">
        <order-header title="我的购物车">
            <template v-slot:tip>
                <span>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</span>
            </template>
        </order-header>
        <div class="wrapper">
            <div class="container">
                <div class="cart-box">
                    <ul class="cart-item-head">
                        <li class="col-1"><span class="checkbox" @click="toggleAll" v-bind:class="{'checked':allChecked}"></span>全选</li>
                        <li class="col-3">商品名称</li>
                        <li class="col-1">单价</li>
                        <li class="col-2">数量</li>
                        <li class="col-1">小计</li>
                        <li class="col-1">操作</li>
                    </ul>
                    <ul class="cart-item-list">
                        <li class="cart-item" v-for="(item,index) in list" v-bind:key="index">
                            <div class="item-check">
                                <span class="checkbox" v-bind:class="{'checked':item.selected}" @click="updateCart(item)"></span>
                            </div>
                            <div class="item-name">
                                <img v-lazy="item.image" alt="">
                                <span>
                                    {{item.title}}
                                    <p style="font-size: 14px; margin-top: 10px;color: #999999">{{item.sku}}</p>
                                </span>

                            </div>
                            <div class="item-price">{{item.price}}</div>
                            <div class="item-num">
                                <div class="num-box">
                                    <a href="javascript:;" @click="updateCart(item,'-')">-</a>
                                    <span>{{item.num}}</span>
                                    <a href="javascript:;"  @click="updateCart(item,'+')">+</a>
                                </div>
                                <p v-if="item.stock < item.num" style="font-size: 13px; color: red; margin-top: 5px">(仅剩{{item.stock}}件)</p>
                            </div>
                            <div class="item-total">{{item.price * item.num|NumFormat}}</div>
                            <div class="item-del" @click="delProduct(item.id)"></div>
                        </li>
                    </ul>
                </div>
                <div class="order-wrap clearfix">
                    <div class="cart-tip fl">
                        <a href="/#/index">继续购物</a>
                        共<span>{{list.length}}</span>件商品，已选择<span>{{checkedNum}}</span>件
                    </div>
                    <div class="total fr">
                        合计：<span>{{cartTotalPrice}}</span>元
                        <a href="javascript:;" class="btn" @click="toMakeOrder">去结算</a>
                    </div>
                </div>
            </div>
        </div>
        <service-bar></service-bar>
        <nav-footer></nav-footer>
    </div>

</template>

<script>
    import NavFooter from "../components/NavFooter";
    import OrderHeader from "../components/OrderHeader";
    import ServiceBar from './../components/ServiceBar'
    export default {
        name: "cart",
        components: {OrderHeader, NavFooter, ServiceBar},
        data() {
            return {
                list:[],//商品列表
                allChecked:false,//是否全选
                cartTotalPrice:0,//商品总金额
                checkedNum:0//选中商品数量
            }
        },
        filters: {
            // 金额显示.00格式
            NumFormat: function (value) {
                if(!value) return '0.00'
                value = value.toFixed(2)
                var intPart = Math.trunc(value)// 获取整数部分
                var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1') // 将整数部分逢三一断
                var floatPart = '.00' // 预定义小数部分
                var value2Array = value.split('.')
                // =2表示数据有小数位
                if(value2Array.length === 2) {
                    floatPart = value2Array[1].toString() // 拿到小数部分
                    if(floatPart.length === 1) { // 补0,实际上用不着
                        return intPartFormat + '.' + floatPart + '0'
                    } else {
                        return intPartFormat + '.' + floatPart
                    }
                } else {
                    return intPartFormat + floatPart
                }
            }
        },
        mounted() {
            this.getList()
        },
        methods: {
            getList() {
                this.http.get('/api/cart/list').then((res)=> {
                    this.renderData(res)
                })
            },
            // 更新购物车数量和购物车单选状态
            updateCart(item,type){
                let buyNum = item.num,
                    selected = item.selected;
                if(type == '-'){
                    if(buyNum == 1){
                        this.message.warning('商品至少保留一件');
                        return;
                    }
                    --buyNum;
                }else if(type == '+'){
                    alert(item.stock)
                    if(buyNum > item.stock){
                        this.message.warning('购买数量不能超过库存数量');
                        return;
                    }
                    ++buyNum;
                }else{
                    selected = !item.selected;
                }
                this.http.post('/api/cart/update',{
                    id: item.id,
                    num: buyNum,
                    selected
                }).then(()=>{
                    //性能低
                    this.getList()
                })
            },

            // 控制全选功能
            toggleAll(){
                let url = this.allChecked?'/api/cart/unSelectAll':'/api/cart/selectAll';
                this.http.get(url).then(()=>{
                    this.getList()
                })
            },
            // 删除购物车商品
            delProduct(id){
                this.http.post('/api/cart/delete', {id}).then(()=>{
                    this.message.success('删除成功');
                    this.getList();
                });
            },
            toMakeOrder() {
                if (this.checkedNum == 0) {
                    this.message.error('请至少选择一件商品')
                    return
                }
                this.$router.push('/orderConfirm')
            },

            // 公共赋值
            renderData(res){
                this.list = res.result.list || [];
                this.allChecked = res.result.checkedAll;
                this.cartTotalPrice = res.result.totalPrice;
                this.checkedNum = res.result.selectedCount;
            },
        }
    }
</script>

<style lang="scss">
    .cart{
        .wrapper{
            background-color:#F5F5F5;
            padding-top:30px;
            padding-bottom:114px;
            .cart-box{
                background-color:#fff;
                font-size:14px;
                color:#999999;
                text-align:center;
                .checkbox{
                    display: inline-block;
                    width: 22px;
                    height: 22px;
                    border: 1px solid #E5E5E5;
                    vertical-align: middle;
                    margin-right: 17px;
                    cursor:pointer;
                    &.checked{
                        background:url('/imgs/icon-gou.png') #FF6600 no-repeat center;
                        background-size:16px 12px;
                        border:none;
                    }
                }
                .cart-item-head{
                    display:flex;
                    height: 79px;
                    line-height: 79px;
                    .col-1{
                        flex:1;
                    }
                    .col-2{
                        flex:2;
                    }
                    .col-3{
                        flex:3;
                    }
                }
                .cart-item-list{
                    .cart-item{
                        display:flex;
                        align-items:center;
                        height:125px;
                        border-top:1px solid #E5E5E5;
                        font-size:16px;
                        .item-check{
                            flex:1;
                        }
                        .item-name{
                            flex:3;
                            font-size: 18px;
                            color: #333333;
                            display: flex;
                            align-items: center;
                            img{
                                width:80px !important;
                                height:80px !important;
                                vertical-align:middle;
                            }
                            span{
                                margin-left: 30px;
                            }
                        }
                        .item-price{
                            flex:1;
                            color:#333333;
                        }
                        .item-num{
                            flex:2;
                            .num-box{
                                display:inline-block;
                                width:150px;
                                height:40px;
                                line-height:40px;
                                border:1px solid #E5E5E5;
                                font-size:14px;
                                a{
                                    display:inline-block;
                                    width:50px;
                                    color:#333333;
                                }
                                span{
                                    display:inline-block;
                                    width:50px;
                                    color:#333333;
                                }
                            }
                        }
                        .item-total{
                            flex:1;
                            color:#FF6600;
                        }
                        .item-del{
                            flex:1;
                            width:14px;
                            height:12px;
                            background:url('/imgs/icon-close.png') no-repeat center;
                            background-size:contain;
                            cursor:pointer;
                        }
                    }
                }
            }
            .order-wrap{
                font-size:14px;
                color: #666666;
                margin-top: 20px;
                height: 50px;
                line-height: 50px;
                .cart-tip{
                    margin-left: 29px;
                    a{
                        color: #666666;
                        margin-right:37px;
                    }
                    span{
                        color:#FF6600;
                        margin:0 5px;
                    }
                }
                .total{
                    font-size:14px;
                    color:#FF6600;
                    span{
                        font-size:24px;
                    }
                    a{
                        width:202px;
                        height:50px;
                        line-height:50px;
                        font-size:18px;
                        margin-left:37px;
                    }
                }
            }
        }
    }
</style>